package com.os.service.impl;

import com.os.dao.EsMetaData;
import com.os.domain.MetaData;
import com.os.service.MetaDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 风亦未止
 * @date 2023/5/3 16:57
 */
@Service
@Slf4j
public class MetaDataServiceImpl implements MetaDataService {

    @Autowired
    private EsMetaData esMateData;

    @Override
    public MetaData findByNameAndVersion(String name, Integer version){
        return esMateData.findMetaDataByNameEqualsAndVersionEquals(name,version);
    }

    @Override
    public List<MetaData> findByName(String name){
        return esMateData.findMetaDataByNameEquals(name);
    }

    @Override
    public MetaData save(MetaData mateData){
        MetaData save = null;
        try {
           save = esMateData.save(mateData);;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return save;
    }

    @Override
    public MetaData findLatestByName(String name) {
        List<MetaData> list = esMateData.findMetaDataByNameEquals(name);
        if(list != null && list.size() != 0){
            List<MetaData>  sorted = list.stream().sorted((a, b) -> {
                return   a.getVersion() - b.getVersion();
            }).collect(Collectors.toList());
            MetaData metaData = sorted.get(list.size() - 1);
            return metaData;
        }
        return null;
    }
}
